﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using UnityScriptEngine;

using System.Drawing.Printing;

namespace EnrollmentSystem
{
    public partial class frmMasterist : Form
    {

        UnityProcessor proc = new UnityProcessor();
        UnityScript[] dat = new UnityScript[0];
        Threader t = new Threader();
        UnityScript[] eudat = new UnityScript[0]; 
        
        DataTable items = new DataTable();
        DataTable itemsDetail = new DataTable();

        DataTable masterList = new DataTable();
        DataTable grades = new DataTable();
        DataTable studentprofile = new DataTable();
        DataTable subject = new DataTable();

        public frmMasterist()
        {
            InitializeComponent();
            InitializeFrameSliderForm();
        }

        private void InitializeForm()
        {

            InitializeItemTable();
            btnPrint.Click +=new EventHandler(btnPrint_Click);
            proc.ProcessCompleted += new ProcessHandler(proc_ProcessCompleted);
            proc.ProcessError += new ProcessHandler(proc_ProcessError);
            btnSearch.Click += new EventHandler(btnSearch_Click);
            InitialData();
        }

        void btnSearch_Click(object sender, EventArgs e)
        {
            pnlMsg.Visible = true;
            LoadSearchData();
        }

        void proc_ProcessError(string id, string desc)
        {
            t.SafeCall(this, delegate
            {
                MessageBox.Show(desc);
                pnlMsg.Visible = false;
            });
        }

        void proc_ProcessCompleted(string id, string desc)
        {
            t.SafeCall(this, delegate
            {
                switch (id)
                {
                    case "LOADSEARCH":
                        
                        proc.DBPUX_Data_Fetch(out eudat);
                        
                        items.Rows.Clear();
                        itemsDetail.Rows.Clear();
                        masterList = eudat[0].ToDataTable();
                        subject = eudat[1].ToDataTable();

                        ConstructItems();
                        grdItems.DataSource = items;

                        for (int i = 0; i < grdItems.Columns.Count; i++)
                            grdItems.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable;

                            pnlMsg.Visible = false;
                        break;
                    case "LOAD":
                        UnityScript[] edat;
                        proc.DBPUX_Data_Fetch(out edat);
                        
                        lstAYsem.Items.Clear();
                        if (edat[0].Data_Count > 0)
                        {
                            lstAYsem.Items.AddRange(edat[0].ToList<string>(0));
                            lstAYsem.SelectedIndex = 0;
                        }
                        break;
                }
            });
        }

        void InitializeItemTable()
        {
            items.Columns.Add("Courses Offered");
            items.Columns.Add("Year Level");
            items.Columns.Add("Male");
            items.Columns.Add("Female");
            items.Columns.Add("Total");

            grdItems.DataSource = items;

            grdItems.Columns[1].DefaultCellStyle.WrapMode = DataGridViewTriState.True;

            grdItems.Columns[2].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            grdItems.Columns[3].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            grdItems.Columns[4].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;


        }
        void InitialData()
        {
            while (proc.IsRunning)
            {
                System.Threading.Thread.Sleep(1);
            }
            proc.ProcStart();
            UnityScript x = new UnityScript("LOAD", 4);
            x.Script_Add(Script.DBPUX_BEGIN);
            x.Script_Add(Script.DBPUX_QUERY, string.Format("SELECT DISTINCT fSchoolYear FROM tblEnrollment"));
            //x.Script_Add);
            x.Script_Add(Script.DBPUX_COMMIT);
            proc.Run(x);
        }
        void LoadSearchData()
        {
            
            UnityScript U = new UnityScript("LOADSEARCH", 4);
            U.Script_Add(Script.DBPUX_BEGIN);
            
            U.Script_Add(Script.DBPUX_QUERY, string.Format("SELECT fID, t1.fEnrollmentNumber, t1.fStudentNumber, ffCourse, fYearLevel, ffSex, fStamp FROM tblEnrollment t1, " +
                    " (SELECT fNumber, fCourse AS ffCourse, fSex AS ffSex FROM tblstudentprofile t22  ORDER BY fCourse ASC) AS t2 " +
                    "WHERE (t1.fStudentNumber = t2.fNumber) AND (fSchoolYear = '{0}')", lstAYsem.Text));
            
            
            U.Script_Add(Script.DBPUX_QUERY, string.Format("SELECT fID, t1.fData, ffYear, fStamp FROM tblLookUp t1 , " +
                    " (SELECT fKey, fData AS ffYear FROM tblLookUp t22) As t2 " +
                    " WHERE (t2.fKey = 'YEAR_LEVEL') AND (t1.fKey = 'COURSES_OFFERED') ORDER BY t1.fData ASC"));
            U.Script_Add(Script.DBPUX_COMMIT);
            proc.Run(U);
        }

        struct eReport
        {
            public string courseOffered;
            public string yearLevel;
            public int  male;
            public int  female;
            public int  total;
        }
        void ConstructItems()
        {
            eReport [] master = new eReport[0];

            string courseOffered = "";
            string yearLevel = "";
            for (int i = 0; i < subject.Rows.Count; i++)
            {
                Array.Resize<eReport>(ref master, master.Length + 1);
                yearLevel = subject.Rows[i][1].ToString();

                if (!courseOffered.Equals(subject.Rows[i][0].ToString()))
                {
                    courseOffered = subject.Rows[i][0].ToString();
                    master[master.Length - 1].courseOffered = courseOffered;
                }
                switch (yearLevel)
                {
                    case "1": master[master.Length - 1].yearLevel = "First Year"; break;
                    case "2": master[master.Length - 1].yearLevel = "Second Year"; break;
                    case "3": master[master.Length - 1].yearLevel = "Third Year"; break;
                    case "4": master[master.Length - 1].yearLevel = "Fourth Year"; break;
                    case "5": master[master.Length - 1].yearLevel = "Fifth Year"; break;
                }
                int MCtr = 0, FCtr = 0, TCtr = 0;
                for (int j = 0; j < masterList.Rows.Count; j++)
                {
                    if (courseOffered.Equals(masterList.Rows[j][2].ToString()))
                    {
                        if (yearLevel.Equals(masterList.Rows[j][3].ToString()) && masterList.Rows[j][4].ToString().Equals("MALE"))
                        {
                            MCtr++;
                            TCtr++;
                        }
                        if (yearLevel.Equals(masterList.Rows[j][3].ToString()) && masterList.Rows[j][4].ToString().Equals("FEMALE"))
                        {
                            FCtr++;
                            TCtr++;
                        }
                    }
                }

                master[master.Length - 1].male = MCtr;
                master[master.Length - 1].female= FCtr;
                master[master.Length - 1].total= TCtr;
            }

            for (int i = 0; i < master.Length; i++)
            {
                DataRow dr = items.NewRow();
                dr[0] = master[i].courseOffered;
                dr[1] = master[i].yearLevel;
                dr[2] = master[i].male;
                dr[3] = master[i].female;
                dr[4] = master[i].total;
                items.Rows.Add(dr);
            }
        }

        //printing
        int cnt = 0;
        int pp = 1;
        void btnPrint_Click(object sender, EventArgs e)
        {
            PrintDocument pd = new PrintDocument();
            pd.DocumentName = lblText.Text;
            pd.PrintPage += new PrintPageEventHandler(pd_PrintPage);
            PrintDialog pdlg = new PrintDialog();
            pdlg.Document = pd;
            if (pdlg.ShowDialog() == DialogResult.OK)
            {
                PrintPreviewDialog ppdlg = new PrintPreviewDialog();
                ppdlg.Document = pd;
                pp = 1;
                //Tracking.EnterLog("Price Table is printed.", DateTime.Now.ToString());
                ppdlg.ShowDialog();
            }
        }

        void pd_PrintPage(object sender, PrintPageEventArgs e)
        {
            float lpp = 0;
            float y = 0;
            float tm = e.MarginBounds.Top;
            float lm = e.MarginBounds.Left - 50;
            float rm = e.PageBounds.Width - 50;
            float bm = e.PageBounds.Height - 100;
            float ht = 0;
            Font cFont;
            StringFormat sf = new StringFormat();


            //Header
            y = 110;
            cFont = new Font("Arial", 11f, FontStyle.Bold);
            ht = cFont.GetHeight(e.Graphics);
            sf.Alignment = StringAlignment.Center;
            e.Graphics.DrawString("GOLDEN WEST COLLEGES", new Font("Arial", 17f, FontStyle.Bold), Brushes.Black, e.PageBounds.Width / 2, 50, sf);
            e.Graphics.DrawString("San Jose Drive, Alaminos City Pangasinan", cFont, Brushes.Black, e.PageBounds.Width / 2, 50+ht+ht, sf);
            e.Graphics.DrawString(""+lstAYsem.Text, cFont, Brushes.Black, e.PageBounds.Width / 2, 50 + ht + ht + ht, sf);
            y += ht;
            y += ht;
            e.Graphics.DrawLine(new Pen(Color.Black), new PointF(lm, y - (ht / 2)), new PointF(rm, y - (ht / 2)));
            cFont = new Font("Arial", 11f, FontStyle.Bold);
            sf.Alignment = StringAlignment.Near;
            e.Graphics.DrawString("Courses Offered", cFont, Brushes.Black, lm, y, sf);
            sf.Alignment = StringAlignment.Far;
            e.Graphics.DrawString("Enrollment", cFont, Brushes.Black, rm - 100, y, sf);
            y += ht;
            
            e.Graphics.DrawString("Male" , cFont, Brushes.Black, lm + 500, y, sf);
            e.Graphics.DrawString("Female" , cFont, Brushes.Black, lm + 590, y, sf);
            e.Graphics.DrawString("Total", cFont, Brushes.Black, lm + 690, y, sf);

            sf.Alignment = StringAlignment.Near;
             y+= ht;
            
            //Data
            y += ht * (1.5f);
            
            ht = cFont.GetHeight(e.Graphics);
            lpp = (bm - y) / ht;
            int cl = 0;
            string name = "";
            int x = 1;
            while (cl <= lpp && cnt < grdItems.Rows.Count)
            {
                
                string str = grdItems.Rows[cnt].Cells[0].Value.ToString();
                if (!name.Equals(str))
                {
                    
                    e.Graphics.DrawString("" + str, cFont, Brushes.Black, lm + 4, y, sf);
                    name = grdItems.Rows[cnt].Cells[1].Value.ToString();
                }

                str = grdItems.Rows[cnt].Cells[1].Value.ToString();
                e.Graphics.DrawString("" + str, cFont, Brushes.Black, lm + 300, y, sf);

                str = grdItems.Rows[cnt].Cells[2].Value.ToString();
                e.Graphics.DrawString("" + str, cFont, Brushes.Black, lm + 470, y, sf);

                str = grdItems.Rows[cnt].Cells[3].Value.ToString();
                e.Graphics.DrawString("" + str, cFont, Brushes.Black, lm + 550, y, sf);

                str = grdItems.Rows[cnt].Cells[4].Value.ToString();
                e.Graphics.DrawString("" + str, cFont, Brushes.Black, lm + 650, y, sf);
                
                    //str = grdItems.Rows[cnt].Cells[5].Value.ToString();
                    //e.Graphics.DrawString("" + str, cFont, Brushes.Black, lm + 720, y, sf);
               
                y += ht * (1.25f);
                cnt++;
                cl++;
            }
            //e.Graphics.DrawString("Total", cFont, Brushes.Blue, stx - 150, y + 10, sf);
            //e.Graphics.DrawString(, cFont, Brushes.Blue, stx - 4, y + 10, sf);

            if (cnt < grdItems.Rows.Count)
            {
                e.HasMorePages = true;
                pp++;
            }
            else
            {
                y += ht;
                e.Graphics.DrawLine(new Pen(Color.Black), new PointF(lm, y - (ht / 2)), new PointF(rm, y - (ht / 2)));
                e.Graphics.DrawString("******************** Nothing Follows ********************", cFont, Brushes.Black, lm + 150, y + ht, new StringFormat());

                pp = 1;
                e.HasMorePages = false;
                cnt = 0;
            }
        }

        
    }
}
